import Toast from 'tdesign-miniprogram/toast/index';
import { getOutfitDetail } from '../../../services/outfit/outfit';

Page({
  data: {
    id: '',
    outfit: null,
    loading: false
  },

  onLoad(options) {
    // 尝试从本地缓存读取搭配数据
    const outfitDetail = wx.getStorageSync('currentOutfitDetail');
    
    if (outfitDetail) {
      this.setData({ outfit: outfitDetail });
      // 清理本地缓存中的数据
      wx.removeStorageSync('currentOutfitDetail');
    } else if (options.id) {
      // 如果本地缓存没有数据，再尝试通过 id 加载 (作为备用)
      this.setData({ id: options.id });
      this.loadOutfitDetail();
    }
  },

  async loadOutfitDetail() {
    // 保留原有的通过 id 加载数据的逻辑，作为备用方案
    try {
      this.setData({ loading: true });
      const res = await getOutfitDetail(this.data.id);
      this.setData({
        outfit: res.data,
        loading: false
      });
    } catch (error) {
      this.setData({ loading: false });
      Toast({
        context: this,
        selector: '#t-toast',
        message: '加载失败',
        icon: 'error'
      });
    }
  },

  onEditOutfit() {
    wx.navigateTo({
      url: `/pages/outfit/edit/index?id=${this.data.id}`
    });
  },

  async onDeleteOutfit() {
    const outfitId = this.data.outfit.id;
    if (!outfitId) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '无法获取搭配ID',
        icon: 'error'
      });
      return;
    }

    try {
      const res = await wx.showModal({
        title: '确认删除',
        content: '确定要删除这个搭配吗？',
        confirmText: '删除',
        confirmColor: '#fa4126'
      });
      
      if (res.confirm) {
        // 模拟删除成功，实际应用中应调用删除接口
        // await deleteOutfit(outfitId);

        // 在静态数据中移除该搭配
        const staticIndex = staticOutfitList.findIndex(item => item.id === outfitId);
        if (staticIndex > -1) {
          staticOutfitList.splice(staticIndex, 1);
          console.log('onDeleteOutfit: 已从静态数据中移除', outfitId);
        }

        Toast({
          context: this,
          selector: '#t-toast',
          message: '删除成功',
          icon: 'success'
        });
        
        // 返回上一页（搭配列表页）并通知刷新
        const eventChannel = this.getOpenerEventChannel();
        if (eventChannel) {
          eventChannel.emit('refreshOutfitList', { deletedId: outfitId });
        }
        wx.navigateBack({
          delta: 1
        });

      } else if (res.cancel) {
        console.log('onDeleteOutfit: 用户取消删除');
      }

    } catch (error) {
      console.error('onDeleteOutfit: 删除失败', error);
      if (error.errMsg !== 'showModal:cancel') { // 排除用户取消的错误
         Toast({
          context: this,
          selector: '#t-toast',
          message: '删除失败',
          icon: 'error'
        });
      }
    }
  },

  previewImage() {
    if (this.data.outfit?.image) {
      wx.previewImage({
        urls: [this.data.outfit.image],
        current: this.data.outfit.image
      });
    }
  }
}); 